package com.lagou;

import com.alibaba.fastjson.JSON;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.HashMap;
import java.util.List;

/**
 * @author: jie.zhao
 * @create: 2021/05/31 16:04
 */
public class ZookeeperSelectNode {


    public HashMap<String, String> getServiceNodeAndData(ZooKeeper zooKeeper) {
        HashMap<String, String> pathToNodeDate = new HashMap<>();

        try {
            List<String> childrens = zooKeeper.getChildren("/service", true);
            childrens.forEach(children->{
                try {
                    Stat exists = zooKeeper.exists("/service/"+children, true);
                    System.out.println(exists);
                    if(exists!=null){
                        byte[] data = zooKeeper.getData("/service/" + children, true, null);
                        String value = new String(data);
                        pathToNodeDate.put(children,value);
                    }
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        return pathToNodeDate;
    }

    public HashMap<String, String> getServiceNodeAndData(ZooKeeper zooKeeper,String path) {
        byte[] data = new byte[0];
        try {
            data = zooKeeper.getData(path, false, null);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String result = new String(data);
        if(result==null || result.length()==0){
            return new HashMap<>();
        }
        return JSON.parseObject(result,HashMap.class);
    }

    public String getServiceNodeAndDataStr(ZooKeeper zooKeeper,String path) {
        byte[] data = new byte[0];
        try {
            data = zooKeeper.getData(path, false, null);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String result = new String(data);
       return result;
    }

}
